import router from '@/router';
import { getToken } from '@/utils/auth';
import { notification } from 'ant-design-vue';
import {LikeOutlined, MessageOutlined,SmileOutlined} from '@ant-design/icons-vue'
import useMessageStore from '@/store/modules/message';
import { MessageType } from '@/api/front/message/types';

export interface SSEData {
  type: string;
  message: string;
  pull: boolean;
}

// 初始化
export const initSSE = (url: any) => {
  if (import.meta.env.VITE_APP_SSE === 'false') {
    return;
  }

  url = url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID;
  const { data, error } = useEventSource(url, [], {
    autoReconnect: {
      retries: 10,
      delay: 3000,
      onFailed() {
        console.log('Failed to connect after 10 retries');
      }
    }
  });

  watch(error, () => {
    console.log('SSE connection error:', error.value);
    error.value = null;
  });

  watch(data, () => {
    console.log('data',data.value)
    if (!data.value) return;
    
    const dataObj = JSON.parse(data.value) as SSEData
    let message = ''
    let icon = null
    if(dataObj.type === MessageType.LIKE){
       message = '您有新的点赞消息';
       icon = ()=>h(LikeOutlined,{style:'color: #1677ff'})
       dataObj.type = MessageType.LIKE_COLLECT
    } else if(dataObj.type === MessageType.COMMENT){
      message = '您有新的评论消息';
      icon = ()=>h(MessageOutlined)
    } else if (dataObj.type === MessageType.COLLECT) {
      message = '您有新的收藏消息';
      icon = ()=>h(LikeOutlined,{style:'color: #1677ff'})
      dataObj.type = MessageType.LIKE_COLLECT
    } else {
      message = '您有新的消息';
      icon = ()=>h(SmileOutlined)
      dataObj.type = null
    }

    if (dataObj.pull) {
      useMessageStore().getRedCount();
    }

    notification.open({
      message: message,
      description: dataObj.message,
      icon: icon,
      onClick: () => {
        router.push({
          path: '/user/message',
          query: {
            type: dataObj.type,
          }
        });
      }
    });
    data.value = null;
  });
};
